// pages/house/RentalHouseDetail/com/form-landlord/form-landlord.js
import api from '../../../../../common/api'
import * as utils from "../../../../../utils/utilsNew";

Component({

  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },

  /**
   * 组件的属性列表
   */
  properties: {
    delId: {
      type: String,
      value: ''
    },
    editInfo: {
      type: Object,
      value: {}
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    _mobile: '',
    _name: '',
    mobile: '',
    name: '',
    id: '',
  },

  /**
   * 组件的数据监听
   */
  observers: {
    editInfo(val) {
      const {
        mobile = '',
          name = '',
          id = ''
      } = val || {}
      this.data._mobile = mobile
      this.data._name = name
      this.setData({
        mobile,
        name,
        id,
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onCancel() {
      this.triggerEvent('cancel')
    },

    onConfirm() {
      const {
        _name,
        _mobile,
        delId,
        id
      } = this.data
      if (!(_name && _name.trim())) {
        wx.showToast({
          icon: 'none',
          title: '名称不能为空',
        })
        return
      }
      if (!(_mobile && _mobile.trim())) {
        wx.showToast({
          icon: 'none',
          title: '手机号不能为空',
        })
        return
      }
      if (!utils.phoneNumberStrictCheck(_mobile)) {
        wx.showToast({
          icon: 'none',
          title: '请输入正确的手机号',
        })
        return
      }
      if (!delId) return
      id ? this.editLandlordPhone({
        delId,
        id,
        _mobile,
        _name,
      }) : this.saveLandlordPhone({
        delId,
        _mobile,
        _name,
      })
    },

    async saveLandlordPhone({
      delId,
      _mobile,
      _name,
    }) {
      const res = await api.saveLandlordPhone({
        hmDelId: delId,
        phoneNumber: _mobile,
        phoneOwner: _name
      })
      if (res && res.data && res.data.isSuccess) {
        wx.showToast({
          icon: 'none',
          title: '添加成功',
        })
        this.triggerEvent('confirm')
      } else {
        wx.showToast({
          icon: 'none',
          title: '添加失败,请稍后再试',
        })
      }
    },

    async editLandlordPhone({
      delId,
      id,
      _mobile,
      _name,
    }) {
      const res = await api.editLandlordPhone({
        hmDelId: delId,
        id: id,
        phoneNumber: _mobile,
        phoneOwner: _name
      })
      if (res && res.data && res.data.isSuccess) {
        wx.showToast({
          icon: 'none',
          title: '编辑成功',
        })
        this.triggerEvent('confirm')
      } else {
        wx.showToast({
          icon: 'none',
          title: '编辑失败,请稍后再试',
        })
      }
    },

    onNameInput(e) {
      this.data._name = e.detail.value
    },

    onMobileInput(e) {
      this.data._mobile = e.detail.value
    },

    onMove() {
      return false
    }

  }
})